<template>
    <div class="container mx-auto md:p-4">
        <!-- 基本信息卡片 - 布局规整化 + 响应式优化 -->
        <el-card
            class="mb-2 shadow-sm rounded-lg border border-slate-200 overflow-hidden"
        >
            <div>
                <!-- 卡片头部 - 优化对齐与响应式换行 -->
                <div
                    class="flex flex-col sm:flex-row justify-between items-start sm:items-center mb-6 gap-4"
                >
                    <h2
                        class="text-[clamp(1rem,2vw,1.25rem)] font-semibold text-slate-700"
                    >
                        基本信息
                    </h2>
                    <div class="flex flex-wrap gap-3">
                        <el-button
                            type="primary"
                            icon="Edit"
                            @click="handleSave"
                            size="default"
                            class="transition-all hover:shadow-md active:shadow-sm"
                        >
                            保存
                        </el-button>
                        <el-button
                            type="default"
                            icon="ArrowLeft"
                            @click="handleBack"
                            size="default"
                            class="transition-all hover:shadow-md active:shadow-sm"
                        >
                            返回
                        </el-button>
                    </div>
                </div>

                <!-- 描述列表 - 修复列数不对称 + 优化对齐 -->
                <el-descriptions
                    :column="4"
                    border
                    class="w-full text-sm md:text-base"
                    :label-style="{
                        backgroundColor: '#f8fafc',
                        fontWeight: 500,
                        padding: '12px 16px',
                    }"
                    :content-style="{ padding: '12px 16px' }"
                    :label-width="130"
                >
                    >
                    <!-- 第一行：4列（正常） -->
                    <el-descriptions-item
                        label="建设单位"
                        label-class-name="text-red-500 font-medium"
                    >
                        管输官网西部塔里木输油气分公司
                    </el-descriptions-item>
                    <el-descriptions-item label="承包单位">
                        宣垣建设集团有限公司
                    </el-descriptions-item>
                    <el-descriptions-item label="合同ID">
                        GWLH34-2024-209
                    </el-descriptions-item>
                    <el-descriptions-item label="合同名称">
                        <div class="line-clamp-2" :title="contractName">
                            {{ contractName }}
                        </div>
                    </el-descriptions-item>

                    <!-- 第二行：3列（通过span=2实现，保持总列数4） -->
                    <el-descriptions-item
                        label="资金来源"
                        label-class-name="text-red-500 font-medium"
                    >
                        国家管网集团专项投资
                    </el-descriptions-item>
                    <el-descriptions-item
                        label="专业类型"
                        label-class-name="text-red-500 font-medium"
                    >
                        油气管道配套工程（土建类）
                    </el-descriptions-item>
                    <el-descriptions-item label="工程分项名称" :span="2">
                        <div class="line-clamp-2" :title="projectSubName">
                            {{ projectSubName }}
                        </div>
                    </el-descriptions-item>

                    <!-- 第三行：4列（修复原布局不对称问题） -->
                    <el-descriptions-item label="施工开始日期">
                        2024-03-15
                    </el-descriptions-item>
                    <el-descriptions-item label="施工结束日期">
                        2024-08-20
                    </el-descriptions-item>
                    <el-descriptions-item label="施工周期">
                        5个月5天
                    </el-descriptions-item>
                    <el-descriptions-item label="施工地点">
                        新疆库尔勒市塔里木输油气分公司库区
                    </el-descriptions-item>

                    <!-- 第四行：4列（补充空项，保持布局整齐） -->
                    <el-descriptions-item label="编制金额(万元)" :span="3">
                        <!-- 占3列，视觉更平衡 -->
                        <span class="font-medium text-slate-700 text-lg"
                            >286.50</span
                        >
                    </el-descriptions-item>
                    <el-descriptions-item />
                    <!-- 空项补位，确保总列数4 -->
                </el-descriptions>
            </div>
        </el-card>

        <!-- 分部分项表格卡片 - 功能补全 + 交互优化 -->
        <el-card
            class="shadow-sm rounded-lg border border-slate-200 overflow-hidden"
        >
            <el-tabs
                v-model="activeName"
                type="card"
                class="demo-tabs"
                @tab-click="handleClick"
            >
                <el-tab-pane label="清单内" name="清单内">
                    <!-- 表格头部 - 优化按钮换行逻辑 -->
                    <div
                        class="flex flex-col sm:flex-row justify-between items-start sm:items-center mb-2 gap-4"
                    >
                        <h2
                            class="text-[clamp(1rem,2vw,1.25rem)] font-semibold text-slate-700"
                        >
                            分部分项
                        </h2>
                        <div class="flex flex-wrap gap-3">
                            <el-button
                                type="primary"
                                icon="Plus"
                                @click="handleAdd"
                                size="default"
                                class="transition-all hover:shadow-md active:shadow-sm"
                            >
                                添加
                            </el-button>
                            <el-button
                                type="danger"
                                icon="Delete"
                                @click="handleDelete"
                                size="default"
                                :disabled="selectedRows.length === 0"
                                class="transition-all hover:shadow-md active:shadow-sm"
                            >
                                删除选中
                            </el-button>
                        </div>
                    </div>

                    <!-- 表格 - 修复输入框语法 + 选中样式优化 -->
                    <div
                        class="overflow-x-auto rounded-md border border-slate-200"
                    >
                        <el-table
                            :data="currentTableData"
                            border
                            class="w-full text-sm"
                            height="330"
                            :header-cell-style="{
                                backgroundColor: '#e6f2ff',
                                color: '#1e40af',
                                fontWeight: 500,
                                padding: '10px 0',
                            }"
                            :row-style="{ height: '56px' }"
                            :cell-style="{ padding: '4px' }"
                            @selection-change="handleSelectionChange"
                            row-key="id"
                            highlight-current-row
                        >
                            <!-- 选中列 - 优化宽度与对齐 -->
                            <el-table-column
                                type="selection"
                                width="55"
                                align="center"
                                :selectable="(row) => row.id !== undefined"
                            ></el-table-column>

                            <!-- 序号列 - 固定 + 居中 -->
                            <el-table-column
                                prop="index"
                                label="序号"
                                width="60"
                                align="center"
                                fixed="left"
                            ></el-table-column>

                            <!-- 编码列 - 可编辑 + 聚焦样式 -->
                            <el-table-column
                                prop="code"
                                label="编码"
                                width="140"
                                align="center"
                            >
                                <template #default="scope">
                                    <el-input
                                        v-model="scope.row.code"
                                        size="small"
                                        placeholder="请输入编码"
                                        class="w-full transition-all focus:border-blue-400 focus:ring-1 focus:ring-blue-400"
                                    ></el-input>
                                </template>
                            </el-table-column>

                            <!-- 单位列 - 居中输入 -->
                            <el-table-column
                                prop="unit"
                                label="单位"
                                width="80"
                                align="center"
                            >
                                <template #default="scope">
                                    <el-input
                                        v-model="scope.row.unit"
                                        size="small"
                                        placeholder="单位"
                                        class="w-full text-center transition-all focus:border-blue-400 focus:ring-1 focus:ring-blue-400"
                                    ></el-input>
                                </template>
                            </el-table-column>

                            <!-- 名称列 - 超出提示优化 -->
                            <el-table-column
                                prop="name"
                                label="名称"
                                min-width="180"
                                align="center"
                            >
                                <template #default="scope">
                                    <el-input
                                        v-model="scope.row.name"
                                        size="small"
                                        placeholder="请输入项目名称"
                                        class="w-full transition-all focus:border-blue-400 focus:ring-1 focus:ring-blue-400"
                                        :show-overflow-tooltip="{
                                            effect: 'dark',
                                            placement: 'top',
                                        }"
                                    ></el-input>
                                </template>
                            </el-table-column>

                            <!-- 项目特征列 - 多行适配 -->
                            <el-table-column
                                prop="feature"
                                label="项目特征"
                                min-width="220"
                                align="center"
                            >
                                <template #default="scope">
                                    <el-input
                                        v-model="scope.row.feature"
                                        size="small"
                                        placeholder="请输入项目特征（如材质、规格）"
                                        class="w-full transition-all focus:border-blue-400 focus:ring-1 focus:ring-blue-400"
                                        :show-overflow-tooltip="{
                                            effect: 'dark',
                                            placement: 'top',
                                        }"
                                    ></el-input>
                                </template>
                            </el-table-column>

                            <!-- 工程量列 - 修复标签闭合 + 数字输入优化 -->
                            <el-table-column
                                prop="quantity"
                                label="工程量"
                                width="120"
                                align="center"
                            >
                                <template #default="scope">
                                    <el-input
                                        v-model.number="scope.row.quantity"
                                        size="small"
                                        placeholder="0.00"
                                        class="w-full text-right transition-all focus:border-blue-400 focus:ring-1 focus:ring-blue-400"
                                        @input="
                                            handleCalculateAmount(scope.$index)
                                        "
                                        type="number"
                                        step="0.01"
                                        min="0"
                                    ></el-input>
                                </template>
                            </el-table-column>

                            <!-- 综合单价列 - 修复标签闭合 -->
                            <el-table-column
                                prop="unitPrice"
                                label="综合单价(元)"
                                width="140"
                                align="center"
                            >
                                <template #default="scope">
                                    <el-input
                                        v-model.number="scope.row.unitPrice"
                                        size="small"
                                        placeholder="0.00"
                                        class="w-full text-right transition-all focus:border-blue-400 focus:ring-1 focus:ring-blue-400"
                                        @input="
                                            handleCalculateAmount(scope.$index)
                                        "
                                        type="number"
                                        step="0.01"
                                        min="0"
                                    ></el-input>
                                </template>
                            </el-table-column>

                            <!-- 金额列 - 只读 + 强调色 -->
                            <el-table-column
                                prop="amount"
                                label="金额(元)"
                                width="140"
                                align="center"
                            >
                                <template #default="scope">
                                    <el-input
                                        v-model="scope.row.amount"
                                        size="small"
                                        class="w-full text-right font-medium text-slate-700 bg-slate-50 cursor-default"
                                        readonly
                                    ></el-input>
                                </template>
                            </el-table-column>

                            <!-- 备注列 - 简洁提示 -->
                            <el-table-column
                                prop="remark"
                                label="备注"
                                min-width="120"
                                align="center"
                            >
                                <template #default="scope">
                                    <el-input
                                        v-model="scope.row.remark"
                                        size="small"
                                        placeholder="备注信息"
                                        class="w-full transition-all focus:border-blue-400 focus:ring-1 focus:ring-blue-400"
                                        :show-overflow-tooltip="{
                                            effect: 'dark',
                                            placement: 'top',
                                        }"
                                    ></el-input>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>

                    <!-- 新增：总金额统计行 - 实用功能补全 -->
                    <div
                        class="mt-4 flex justify-end items-center gap-4 p-3 bg-slate-50 rounded-md border border-slate-200"
                    >
                        <span class="text-slate-700 font-medium"
                            >分部分项合计（元）：</span
                        >
                        <span class="text-red-500 font-semibold text-lg">{{
                            totalAmount
                        }}</span>
                    </div>

                    <!-- 空状态提示 - 优化样式 -->
                    <div
                        v-if="currentTableData.length === 0"
                        class="text-center py-16 text-slate-500"
                    >
                        <el-empty
                            description="暂无分部分项数据，点击「添加」按钮创建"
                            :image-size="120"
                        ></el-empty>
                    </div>
                </el-tab-pane>
                <el-tab-pane label="变更及签证" name="变更及签证"
                    >变更及签证</el-tab-pane
                >
                <el-tab-pane label="扣款" name="扣款">扣款</el-tab-pane>
            </el-tabs>
        </el-card>
    </div>
</template>

<script setup>
import { ref, computed } from "vue";
import { ElMessage, ElEmpty } from "element-plus"; // 补全ElEmpty导入
import { useRouter } from "vue-router";
const router = useRouter();

// 引入图标（确保图标存在）
import { Edit, ArrowLeft, Plus, Delete } from "@element-plus/icons-vue";

// 基本信息假数据（优化命名与维护性）
const contractName =
    "西部管道塔里木分公司2024年憋压库气站、库尔勒维抢修中心办公及生活后勤标准化建设合同";
const projectSubName =
    "西部管道塔里木分公司2024年憋压库气站设备基础改造、库尔勒维抢修中心办公楼翻新及附属设施建设";

// 分部分项假数据（丰富数据 + 新增id字段优化选中）
const contractData = ref([
    {
        id: 1,
        index: 1,
        code: "041001002001",
        unit: "m²",
        name: "拆除人行道",
        feature:
            "1.材质：混凝土预制砖 2.厚度：100mm 3.拆除后垃圾清理至指定地点",
        quantity: 85.6,
        unitPrice: 45.8,
        amount: (85.6 * 45.8).toFixed(2),
        remark: "库区入口处人行道",
    },
    {
        id: 2,
        index: 2,
        code: "041001001001",
        unit: "m²",
        name: "拆除路面",
        feature: "1.材质：沥青混凝土 2.厚度：150mm 3.拆除范围：设备运输通道",
        quantity: 120.3,
        unitPrice: 68.2,
        amount: (120.3 * 68.2).toFixed(2),
        remark: "承重路面，需分段拆除",
    },
    {
        id: 3,
        index: 3,
        code: "011607001001",
        unit: "m²",
        name: "阳光板屋面拆除",
        feature: "1.材质：PC阳光板 2.骨架：铝合金 3.拆除后回收可利用材料",
        quantity: 42.8,
        unitPrice: 125.5,
        amount: (42.8 * 125.5).toFixed(2),
        remark: "库房屋面老化更换",
    },
    {
        id: 4,
        index: 4,
        code: "011608002001",
        unit: "m²",
        name: "铲除涂料面",
        feature: "1.部位：办公楼内墙 2.涂料类型：乳胶漆 3.铲除至基层",
        quantity: 380.5,
        unitPrice: 18.6,
        amount: (380.5 * 18.6).toFixed(2),
        remark: "墙面翻新前处理",
    },
    {
        id: 5,
        index: 5,
        code: "011606001001",
        unit: "m²",
        name: "楼地面龙骨及饰面拆除",
        feature: "1.龙骨：实木 2.饰面：复合地板 3.拆除范围：办公室3-5层",
        quantity: 210.7,
        unitPrice: 89.3,
        amount: (210.7 * 89.3).toFixed(2),
        remark: "地板老化更换",
    },
    {
        id: 6,
        index: 6,
        code: "011201001001",
        unit: "m²",
        name: "墙面一般抹灰",
        feature: "1.部位：设备基础外墙 2.厚度：20mm 3.砂浆强度：M5.0",
        quantity: 156.2,
        unitPrice: 32.8,
        amount: (156.2 * 32.8).toFixed(2),
        remark: "基础防护处理",
    },
    {
        id: 7,
        index: 7,
        code: "020101001001",
        unit: "m²",
        name: "水泥砂浆楼地面",
        feature: "1.厚度：50mm 2.砂浆强度：C20 3.部位：设备操作间",
        quantity: 98.4,
        unitPrice: 78.5,
        amount: (98.4 * 78.5).toFixed(2),
        remark: "耐磨地面要求",
    },
    {
        id: 8,
        index: 8,
        code: "030404017001",
        unit: "套",
        name: "配电箱安装",
        feature: "1.规格：800*600*200mm 2.材质：冷轧钢板 3.含内部接线",
        quantity: 6,
        unitPrice: 1280.5,
        amount: (6 * 1280.5).toFixed(2),
        remark: "各功能区配电改造",
    },
    {
        id: 9,
        index: 9,
        code: "010502001001",
        unit: "m³",
        name: "矩形柱",
        feature: "1.混凝土强度：C30 2.截面尺寸：400*400mm 3.部位：办公楼门厅",
        quantity: 8.6,
        unitPrice: 485.2,
        amount: (8.6 * 485.2).toFixed(2),
        remark: "结构加固",
    },
    {
        id: 10,
        index: 10,
        code: "010801001001",
        unit: "樘",
        name: "木质门安装",
        feature: "1.材质：实木复合 2.规格：900*2100mm 3.含门锁五金",
        quantity: 15,
        unitPrice: 860.8,
        amount: (15 * 860.8).toFixed(2),
        remark: "办公室门更换",
    },
]);

// 当前表格数据（深拷贝，避免原数据污染）
const currentTableData = ref(JSON.parse(JSON.stringify(contractData.value)));

// 选中的行数据
const selectedRows = ref([]);
const activeName = ref("清单内");

const handleClick = (tab, event) => {
    console.log(tab, event);
};
// 监听选中事件
const handleSelectionChange = (val) => {
    selectedRows.value = val;
};

// 「添加」按钮逻辑（优化默认值，空值而非0）
const handleAdd = () => {
    const newId = currentTableData.value.length
        ? Math.max(...currentTableData.value.map((item) => item.id)) + 1
        : 1;
    const newIndex = currentTableData.value.length + 1;

    currentTableData.value.push({
        id: newId,
        index: newIndex,
        code: "",
        unit: "",
        name: "",
        feature: "",
        quantity: null, // 空值而非0，避免用户混淆
        unitPrice: null,
        amount: "0.00",
        remark: "",
    });
};

// 「删除」按钮逻辑（优化提示文案）
const handleDelete = () => {
    if (!selectedRows.value.length) {
        ElMessage.warning("请先勾选要删除的分部分项数据");
        return;
    }

    const selectedIds = selectedRows.value.map((item) => item.id);
    currentTableData.value = currentTableData.value.filter(
        (item) => !selectedIds.includes(item.id)
    );

    // 重新生成序号（确保连续）
    currentTableData.value.forEach((item, idx) => {
        item.index = idx + 1;
    });

    selectedRows.value = [];
    ElMessage.success(`成功删除 ${selectedIds.length} 条分部分项数据`);
};

// 自动计算金额（优化空值处理）
const handleCalculateAmount = (index) => {
    const row = currentTableData.value[index];
    // 处理空值/NaN，转为0计算
    const quantity = isNaN(Number(row.quantity)) ? 0 : Number(row.quantity);
    const unitPrice = isNaN(Number(row.unitPrice)) ? 0 : Number(row.unitPrice);
    // 保留两位小数，避免浮点误差
    row.amount = (quantity * unitPrice).toFixed(2);
};

// 返回逻辑
const handleBack = () => {
    router.back();
};

// 保存逻辑（优化验证逻辑，区分空值与0）
const handleSave = () => {
    // 验证必填项：编码、名称不为空，工程量/单价为有效数字
    const invalidItems = currentTableData.value.filter(
        (item) =>
            !item.code.trim() ||
            !item.name.trim() ||
            isNaN(Number(item.quantity)) ||
            isNaN(Number(item.unitPrice)) ||
            Number(item.quantity) < 0 ||
            Number(item.unitPrice) < 0
    );

    if (invalidItems.length) {
        ElMessage.warning(
            `存在 ${invalidItems.length} 条无效数据：\n1. 编码/名称不可为空\n2. 工程量/单价需为非负数字`
        );
        return;
    }

    // 模拟接口请求（添加加载状态提示）
    ElMessage.info("正在保存数据...");
    setTimeout(() => {
        ElMessage.success("结算工作量数据保存成功！");
        // 实际项目中添加接口调用逻辑
    }, 800);
};

// 计算总金额（优化精度）
const totalAmount = computed(() => {
    const total = currentTableData.value.reduce((sum, item) => {
        return sum + Number(item.amount || 0);
    }, 0);
    // 保留两位小数，避免显示多位小数
    return total.toFixed(2);
});
</script>

<style scoped>
/* 优化描述列表对齐与边框 */
.el-descriptions__row {
    border-bottom: 1px solid #e5e7eb !important;
}
.el-descriptions__row:last-child {
    border-bottom: none !important;
}
.el-descriptions__label {
    text-align: right !important;
    border-right: 1px solid #e5e7eb !important;
}

/* 优化表格选中行样式 */
::v-deep .el-table__body tr.current-row > td {
    background-color: #f0f7ff !important;
}
::v-deep .el-table__body tr:hover > td {
    background-color: #f9fafb !important;
}

/* 优化输入框样式（避免过宽） */
::v-deep .el-input--small {
    width: 100% !important;
}
::v-deep .el-input__inner {
    border-radius: 4px !important;
    border-color: #d1d5db !important;
}

/* 响应式调整：小屏幕下描述列表优化 */
@media (max-width: 640px) {
    ::v-deep .el-descriptions__label {
        text-align: left !important;
        border-right: none !important;
        margin-bottom: 4px !important;
    }
}

/* 优化空状态样式 */
::v-deep .el-empty__description {
    color: #6b7280 !important;
    margin-top: 12px !important;
}
</style>
